package org.west.sky.experience.io.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;

/**
 * author: chz
 * date: 2024/2/2
 * description:
 */
public class NioClient {

    public static void main(String[] args) throws IOException {
        // 创建SocketChannel并指定ip地址和端口号
        SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress( 4444));
        System.out.println("NIO 客户端启动=================");
        // 设置非阻塞模式
        socketChannel.configureBlocking(false);
        String hello = "hello";
        ByteBuffer byteBuffer = ByteBuffer.wrap(hello.getBytes());
        // 向通道中写入数据
        socketChannel.write(byteBuffer);
        System.out.println("发送消息:" + hello);
        byteBuffer.clear();
        byteBuffer = ByteBuffer.allocate(1024);
        socketChannel.register(Selector.open(), SelectionKey.OP_READ, byteBuffer);
        while (true) {
            int len = socketChannel.read(byteBuffer);
            if (len > 0) {
                byteBuffer.flip();
                System.out.println("收到服务端消息：" + new String(byteBuffer.array(), 0, len));
            }
            byteBuffer.clear();
            if(new String(byteBuffer.array(), 0, len).toString().contains("client")){
                break;
            }
        }
        socketChannel.shutdownInput();
        socketChannel.close();
        System.out.println("NIO 客户端关闭==================");
    }
}
